<?php

namespace app\admin\model;

/**
 * 栏目-模型
 * Class Category
 * @package app\admin\model
 */
class Category extends BaseModel
{
    // 设置数据表名
    protected $name = 'category';

    /**
     * 获取数据信息
     * @param int $id 栏目ID
     * @return 数据信息|mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     *
     */
    public function getInfo($id)
    {
        $info = parent::getInfo($id); // TODO: Change the autogenerated stub
        if ($info) {
            // 封面
            if ($info['cover']) {
                $info['cover'] = get_image_url($info['cover']);
            }
        }
        return $info;
    }

    /**
     * 获取栏目名称
     * @param $cateId 栏目ID
     * @param string $delimiter 分隔符
     * @return string|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     *
     */
    public function getCateName($cateId, $delimiter = "")
    {
        do {
            $info = $this->getInfo($cateId);
            $names[] = $info['name'];
            $cateId = $info['pid'];
        } while ($cateId > 0);
        if (!empty($names)) {
            $names = array_reverse($names);
            if (count($names) >= 2) {
                if (strpos($names[1], $names[0]) === 0) {
                    unset($names[0]);
                }
            }
            return implode($delimiter, $names);
        }
        return null;
    }

    function getSubs($catId=0){
        $ids=array();
        $categorys = $this->where('pid', $catId)->where('mark', 1)->select();
        foreach($categorys as $item){
            if($item['pid']==$catId){
                $ids[]=$item['id'];
                $ids=array_merge($ids,$this->getSubs($item['id']));

            }
        }
        return $ids;
    }

    /**
     * 获取课程数量
     * @return array
     */
    public function getArticleCount($cateId)
    {
        do {
            $info = $this->getInfo($cateId);
            $ids[] = $info['id'];
            $this->where('pid', $info['id'])->select();
            $cateId = $info['pid'];
        } while ($cateId > 0);
        return $ids;
    }

}